﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using Newtonsoft.Json;

namespace TestHttpPost.Tools
{
    public partial class FormatChange : Form
    {
        public FormatChange()
        {
            InitializeComponent();
        }

        private void textBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            textBox1.SelectAll();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                var ctx = textBox1.Text.Trim(new[] {' ','\t','\r','\n'});
                if (string.IsNullOrWhiteSpace(ctx))
                {
                    return;
                }
                if (ctx.StartsWith("<"))//xml
                {
                    var doc=new XmlDocument();
                    doc.LoadXml(ctx);
                    ctx = JsonConvert.SerializeXmlNode(doc);
                }
                if (ctx.StartsWith("{"))//Json
                {
                    var obj = JsonConvert.DeserializeObject < Dictionary<string, string>>(ctx);
                    if (checkBox1.Checked)
                    {
                        var formContent = new FormUrlEncodedContent(obj);

                        textBox2.Text = formContent.ReadAsStringAsync().Result;

                    }
                    else
                    {
                        textBox2.Text = string.Join("&", obj.Select(p => $"{p.Key}={p.Value}"));
                    }
                    textBox2.Focus();
                    textBox2.SelectAll();
                }

            }
            catch (Exception)
            {
                
                throw;
            }
        }
    }
}
